package com.suo.web;

import com.alibaba.fastjson.JSON;
import com.suo.mapper.UserMapper;
import com.suo.pojo.User;
import com.suo.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "loginServlet", value = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

        SqlSession sqlSession = sqlSessionFactory.openSession();

        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        String userStr = request.getReader().readLine();

        User user = JSON.parseObject(userStr, User.class);

        User select = mapper.select(user.getName(), user.getPassword());

        if(select == null) {
            response.getWriter().write("0");
        } else {
            String remember = request.getParameter("remember");
            if("1".equals(remember)) {
                Cookie c_username = new Cookie("username",user.getName());
                Cookie c_password = new Cookie("password",user.getPassword());

                c_username.setMaxAge(60*60*24);
                c_password.setMaxAge(60*60*24);

                response.addCookie(c_username);
                response.addCookie(c_password);
            }
            request.getSession().setAttribute("username",user.getName());
            response.getWriter().write("1");
        }

        sqlSession.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
